package org.spbsu.apco.common.task.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spbsu.apco.common.task.core.BaseTask;
import org.springframework.util.Assert;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Generic task to emulate computations.
 * <p/>
 * User: mikpan
 * Date: 3/29/13
 * Time: 4:38 PM
 */
public class GenericCommunicationTask extends BaseTask<String, Integer> {
    private static final Logger LOG = LoggerFactory.getLogger(GenericCommunicationTask.class);

    public GenericCommunicationTask() {
    }

    @Override
    public Integer execute(List<String> inputData) throws Exception {
        Assert.notEmpty(inputData, "Input is empty.");

        for (String address : inputData) {
            doDownloadData(address);
        }

        return 0;
    }

    private void doDownloadData(String fromURL) throws Exception {
        String tempFile = "temp-" + new Random().nextInt(100);
        try {
            URL website = new URL(fromURL);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.err.println("Temp file: " + new File(tempFile).getAbsolutePath());
            throw e;
        } finally {
            File tf = new File(tempFile);
            LOG.info("Removing file: {}", tf.getAbsolutePath());
            tf.delete(); //TODO: check whether it induces sufficient delay
        }
    }

    public static void main(String[] args) throws Exception {
        List<String> links = new ArrayList<String>();
        for (int year = 2009; year <= 2011; year++) {
            links.add("http://fias.uni-frankfurt.de/publi/annualreport" + year + ".pdf");
        }

        GenericCommunicationTask task = new GenericCommunicationTask();
        task.runTask(links);
        System.out.println("Taken " + task.getTaskDuration() / 1000 + "sec to download: " + links);
    }


}

